<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区 -->
    <el-card class="box-card">
      <!--搜索区 和添加用户区 -->
      <el-row :gutter="40">
        <el-col :span="10">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
              clearable
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用戶</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              class="el-icon-edit"
              @click="editUser(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              class="el-icon-delete"
              @click="delUser(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              content="分配角色"
              effect="dark"
              placement="top"
              :enterable="false"
              style="margin-left: 10px"
            >
              <el-button
                type="warning"
                class="el-icon-user-solid"
                @click="selecRole"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户 对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="30%"
      @close="addDialogClosed"
    >
      <!-- 对话框主体内容区 -->
      <el-form
        ref="addFormRef"
        :model="addUserForm"
        label-width="80px"
        :rules="addUserFormRules"
      >
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户 对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="dialogVisible"
      width="30%"
      @close="addDialogClosed"
    >
      <!-- 对话username框主体内容区 -->
      <el-form
        ref="aditFormRef"
        :model="aditUserForm"
        label-width="80px"
        :rules="addUserFormRules"
      >
        <el-form-item label="用户名称" prop="username" disabled>
          <el-input v-model="aditUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="aditUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="aditUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editsure">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 对话款 -->
    <el-dialog title="分配角色" :visible.sync="dialogVisible" width="30%">
      <p>当前的用户:{{ userInfo.username }}</p>
      <p>当前的角色:{{ userInfo.username }}</p>
      <p>
        分配角色：
        <el-select v-model="selectedRoleId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.authName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="savdRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱规则
    // var checkemail=(rule, value, cb) => {
    //   const regEmaile = /^([a-zA-Z0-9-~])+@([a-zA-9_-])+(\.[a-zA-Z0_-])+/
    //   if (regEmaile.test(value)) {
    //     // 合法邮箱
    //     return cb()
    //   }
    //   cb(new Error('请输入合法的邮箱'))
    // }
    // 验证手机规则
    // var checkmobile=(rule, value, cb)=>{
    //    const regEmaile = /^(0|86|17951)？(13[0-9]|15[0123456789]|17[678]|18[0-9]14[57])[0-9]{8}$/
    //   if (regEmaile.test(value)) {
    //   // 合法
    //     return cb()
    //   }
    //   cb(new Error('请输入正确的手机号'))
    // },
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pageSize: 2,
      },
      userList: [
        {
          id: 25,
          username: '张三',
          mobile: 18743674772,
          type: 1,
          email: 'trge112@163.com',
          create_time: '2022-11-15',
          mg_state: true,
          role_name: '管理员',
        },
      ],
      total: 0,
      dialogVisible: false,
      // 添加表单用户数据
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 18,
            message: '长度在 6 到 18 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          // {validator:checkemail}
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          // {validator:checkemail}
        ],
      },
      aditUserForm: {},
      // 需要被分配角色的用户数据
      userInfo: [],
      // 所有角色数据
      rolesList: [],
      // 已选中的角色id
      selectedRoleId: '',
    }
  },
  created() {
    // this.getUserList()
  },
  methods: {
    // 获取用户列表数据
    async getUserList() {
      const { data: res } = await this.$http.get('user', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userList = res.data.userLis
      this.total = res.data.total
    },
    // 监听每页条数改变时
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.queryInfo.pageSize = val
      this.getUserList()
    },
    // 监听页面
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    // 监听开关状态的改变
    async userStateChange(val) {
      const { data: res } = await this.$http.put(
        `users/${val.id}/state/${val.mg_state}`
      )
      if (res.meta.status !== 200) {
        // 更新失败 状态不变
        this.val.mg_state = !val.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 监听添加用户对话框关闭时间
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮 添加用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        // 校验正确添向接口添加用户
        const { data: res } = await this.$http.post('user', this.addUserForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.dialogVisible = false
        this.getUserList()
      })
    },

    // 编辑用户信息
    async editUser(id) {
      this.dialogVisible = true
      const { data: res } = await this.$http.get('users/+id')
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户列表失败')
      }
      this.editForm = res.data
      this.dialogVisible = false
    },
    // 确认 编辑
    editsure() {
      this.$refs.aditFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          'user/' + this.aditUserForm,
          { email: this.editForm.email, mobile: this.editForm.mobile }
        )
        if (res.meta.status !== 201) {
          this.message.error('编辑用户失败')
        }
        this.$message.success('编辑用户成功')
        this.dialogVisible = false
        this.getUserList()
      })
    },
    // 删除用户
    async delUser(id) {
      const del = await this.$confirm(
        '此操作将永久删除该用戶, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // 刪除 确认    放回字符串confirm
      // 刪除 取消    放回字符串cancel
      if (del !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('user/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      this.getUserList()
    },
    // 分配角色 对话框
    async selecRole() {
      // 在展示对话款之气那，获取所有角色的列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('获取角色数据失败')
      }
      this.rolesList = res.data
      this.dialogVisible = true
    },
    // 保存
    async savdRole() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put('user/role', {
        rid: this.selectedRoleId,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('更新角色失败')
      }
      this.$message.success('更新角色成功')
      this.getUserList()
      this.dialogVisible = false
    },
  },
}
</script>

<style scoped>
.el-breadcrumb {
  margin-bottom: 15px;
}
.el-table {
  margin: 15px 0;
  font-size: 12px;
}
</style>
